package com.mtjx.service.impl;

import com.mtjx.entitys.LoginUser;
import com.mtjx.entitys.dto.LoginDTO;
import com.mtjx.resp.VfResult;
import com.mtjx.service.LoginService;
import com.mtjx.utils.JwtUtil;
import com.mtjx.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author 33117
 * @version 1.0
 * @data 2025/8/29 10:08
 */
@Service
public class LoginSserviceImpl implements LoginService {
    // 设置redis有效期
    public static final Long REDIS_TTL = 60 * 60 * 1000L;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public VfResult login(LoginDTO loginDTO) {
        // 进行认证
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(loginDTO.getName(), loginDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 认证没通过 抛出异常
        if (Objects.isNull(authenticate)) {
            return VfResult.errorMsg("登录失败");
        }
        // 生成jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(id);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("token", jwt);
        // 存redis
        loginUser.setToken(jwt);
        redisCache.setCacheObject("login:" + id, loginUser, Math.toIntExact(REDIS_TTL), TimeUnit.MILLISECONDS);
        return VfResult.build(200, "登录成功", hashMap);
    }
}
